<template>
    <div>
        <div class="nav bg-theme color-f text-l">
            <div style="display:flex;flex:2;">
                <i class="iconfont icon-fanhui font19 pl08 iback" @click="goBack"></i>
                <!-- 详情进入 -->
                <span class="font19 ml16">
                    递交
                </span>
            </div>
        </div>

        <div style="padding: 50px 0;">
            <van-field v-model="message" rows="5" autosize label="" type="textarea" class="border-b-1"
                placeholder="请输入您的意见" />
            <div @click="addOpnion" class="addOp">
                <i class="iconfont icon-add color-9 font14 mr5"></i>
                <span class="font14 color-3 oncenter">常用意见</span>
            </div>
            <van-popup v-model="opnionPicker" position="bottom">
                <van-picker show-toolbar :columns="opnionList" @confirm="opnionConfirm" @cancel="opnionPicker = false" />
            </van-popup>
            <div class="bge"></div>

            <!-- 选择抄送人员 -->
            <div v-if="hasCopy" class="copyDiv" @click="toSelectCopy">
                <div class="color-8 font12">选择抄送人员：</div>
                <div style="margin-top:5px;" class="color-8 font13">
                    <span v-for="(item, index) in copyList" :key="item.id">
                        <span class="font13 color-8" v-if="index == 0">{{
                            item.name
                        }}</span>
                        <span class="font13 color-8" v-else>,{{ item.name }}</span>
                    </span>
                </div>
            </div>

            <div class="bge"></div>
            <div class="decisionList">
                <van-radio-group v-model="decisionRadio" @change="decisionChange">
                    <van-radio v-for="item in decisions" :key="item.id" :name="item.id" class="font14 ht40"
                        @click="decisionClick(item.id)">
                        {{ item.decisionName }}
                        <div v-if="decisionRadio == item.id && !selectData" class="color-9 font14">
                            {{ uListName }}
                        </div>
                        <div v-if="decisionRadio == item.id && selectData" class="color-9 font14">
                            <div v-if="selectData.length > 0 && selectData.length < 6" class="color-9 font14">
                                <span v-for="(item2, index2) in selectData" :key="item2.id">
                                    <span v-if="index2 == 0">{{ item2.name }}</span>
                                    <span v-else>,{{ item2.name }}</span>
                                </span>
                            </div>
                            <div v-else-if="selectData.length >= 6" class="color-9 font14">
                                <span v-for="(item3, index3) in selectDataover" :key="item3.id">
                                    <span v-if="index3 == 0">{{ item3.name }}</span>
                                    <span v-else-if="index3 < 6">,{{ item3.name }}</span>
                                    <span v-else>等{{ selectData.length }}人</span>
                                </span>
                            </div>
                            <span v-else>{{ selectData.name }}</span>
                        </div>
                        <div v-if="decisionRadio == item.id && decision == 'end'" class="color-9 font14">
                            当前决策项无需候选人
                        </div>
                    </van-radio>
                </van-radio-group>
            </div>

            <div class="pof-btn">
                <van-button @click="submitClick" :loading="isSubmit" loading-text="提交中" block
                    class="bg-theme color-f ht46 font17">提交</van-button>
            </div>
        </div>
    </div>
</template>
<script>
import { Toast, Notify } from 'vant'
import { getOrgAndUser } from '@/api/public'
import { dyytGetDecisions, dyytGetNextUser, dyytSubmitProcess } from "@/api/dwdyytAPI";
import { mapGetters } from 'vuex'
export default {
    computed: {
        ...mapGetters(['user'])
    },
    data() {
        return {
            message: '', // 意见
            opnionPicker: false,
            opnionList: ['同意', '不同意', '请审批', '请修改', '已阅'],
            params: {}, // 上个页面传过来的数据
            decisions: [], // 决策项
            decisionRadio: '',
            isSubmit: false, // 按钮是否处于提交状态
            isMore: false, // 是否多选
            uList: [], // 人
            uListName: '',
            copyDecision: {}, // 抄送决策项---》是指决策项的类型是否为抄送决策项
            hasCopy: false, // 当前选中的决策项是否含有抄送
            copyList: [], // 抄送所选的人
            selectData: null, // 已经在选人页面选过的人或者组织
            decision: '',
            selectDataover: null, //
        }
    },
    activated() {
        this.params = this.$route.params
        console.log('formData' + this.params.formData)
        this.getDecisions()
        // 缓存

        if (
            localStorage.getItem('searchParams') != '{}' &&
            !!localStorage.getItem('searchParams')
        ) {
            this.params = JSON.parse(localStorage.getItem('searchParams'))
            this.params = Object.assign({ ...this.params.oldParams }, this.params)
            this.decisionRadio = this.params.currentDecision
            localStorage.setItem('searchParams', '{}')
        }
        if (
            localStorage.getItem('searchKeyword') != '{}' &&
            !!localStorage.getItem('searchKeyword')
        ) {
            if (this.params.isCopy == 'false') {
                this.selectData = JSON.parse(localStorage.getItem('searchKeyword'))
                if (this.selectData.length > 6) {
                    this.selectDataover = this.selectData.slice(0, 7)
                    console.log('AAAAAAAAAAAAAA' + JSON.stringify(this.selectDataover))
                    console.log('BBBBBBBBBBBBBBB' + JSON.stringify(this.selectData))
                }
            } else if (this.params.isCopy == 'true') {
                this.copyList = JSON.parse(localStorage.getItem('searchKeyword'))
                this.selectData = this.params.selectPeople
            }
            localStorage.setItem('searchKeyword', '{}')
        }
    },
    watch: {},
    created() {
        // console.log("决策项传参2222",this.params);
        // console.log("vvvv",this.selectData, 'bbbb',this.copyList);
        // console.log("vvvv",this.selectData);
    },
    methods: {
        goBack() {
            this.params = {};
            this.selectData = null;
            this.decisions = [];
            this.decisionRadio = '';
            this.uList = [];
            this.uListName = '';
            this.copyDecision = {};
            this.hasCopy = false;
            this.copyList = [];
            this.decision = '';
            this.$router.back(-1) //返回上一页
        },

        // 获取决策项
        getDecisions() {
            // console.log('this.params.type'+this.params.type)
            // 待办的流程下一步
            Toast.loading({
                message: "加载中...",
                forbidClick: false,
            });
            console.log('tuserName:' + this.user.userName)
            dyytGetDecisions(Object.assign(this.params, { userName: this.user.userName }))
                .then((res) => {
                    Toast.clear();
                    this.decisions = [];
                    if (res.data && res.data.data) {
                        this.decisions = res.data.data;
                    }
                    //   if (res.data && res.data.length > 0) {
                    //     // 判断是否有---> 抄送决策项
                    //     // 判断是从待办还是待阅过来的--待办过来的判断decisionId,待阅过来的判断decisionName
                    //     if (this.params.type == 'task') {
                    //       for (var i in res.data) {
                    //         if (res.data[i].decisionId.indexOf('copy') > -1) {
                    //           // 存在抄送决策项
                    //           this.copyDecision = res.data[i]
                    //         } else {
                    //           this.decisions.push(res.data[i])
                    //         }
                    //       }
                    //     }
                    //     if (this.params.type == 'toRead') {
                    //       for (var i in res.data) {
                    //         if (res.data[i].decisionName.indexOf('copy') > -1) {
                    //         } else {
                    //           this.decisions.push(res.data[i])
                    //         }
                    //       }
                    //     }
                    //     for (var i in this.decisions) {
                    //       if (this.decisions[i].id == this.decisionRadio) {
                    //         this.message = this.decisions[i].opinion
                    //         var config = this.decisions[i].decisionConfig.replace(
                    //           /&quot;/g,
                    //           '"'
                    //         )
                    //         config = JSON.parse(config)
                    //         for (var j in config) {
                    //           if (
                    //             config[j].type == 'activiType' &&
                    //             config[j].typeValue == 'copy'
                    //           ) {
                    //             // 判断当前决策项是否含有抄送
                    //             this.hasCopy = true
                    //             // this.copyList = [];
                    //           }
                    //         }
                    //       }
                    //     }
                    //   }
                }).catch(() => {
                    Toast.clear();
                })

        },
        // 添加常用意见
        addOpnion() {
            this.opnionPicker = true
        },
        opnionConfirm(value) {
            this.message = value
            this.opnionPicker = false
        },
        // 决策项改变
        decisionChange(name) {
            this.uListName = ''
            this.selectData = null
            this.copyList = []
            this.hasCopy = false
            for (var i in this.decisions) {
                if (this.decisions[i].id == name) {
                    this.message = this.decisions[i].opinion
                    this.decision = this.decisions[i].decisionId
                    // 根据决策项判断是否多选，是否必须选人
                    var config = this.decisions[i].decisionConfig.replace(/&quot;/g, '"')
                    config = JSON.parse(config)
                    for (var j in config) {
                        if (
                            config[j].type == 'activiType' &&
                            config[j].typeValue == 'copy'
                        ) {
                            // 判断当前决策项是否含有抄送
                            this.hasCopy = true
                        }
                    }
                    if (
                        this.decisions[i].decisionId == 'end' ||
                        this.decisions[i].decisionId.indexOf('end') > -1
                    ) {
                        this.decision = this.decisions[i].decisionId
                    }
                    this.getOrgAndUser(this.decisions[i])
                }
            }
        },
        decisionClick(name) {
            this.uListName = ''
            this.selectData = null
            this.copyList = []
            this.hasCopy = false
            for (var i in this.decisions) {
                if (this.decisions[i].id == name) {
                    this.message = this.decisions[i].opinion
                    this.decision = this.decisions[i].decisionId
                    // 根据决策项判断是否多选，是否必须选人
                    var config = this.decisions[i].decisionConfig.replace(/&quot;/g, '"')
                    config = JSON.parse(config)
                    for (var j in config) {
                        if (
                            config[j].type == 'activiType' &&
                            config[j].typeValue == 'copy'
                        ) {
                            // 判断当前决策项是否含有抄送
                            this.hasCopy = true
                        }
                    }
                    if (
                        this.decisions[i].decisionId == 'end' ||
                        this.decisions[i].decisionId.indexOf('end') > -1
                    ) {
                        this.decision = this.decisions[i].decisionId
                    }
                    this.getOrgAndUser(this.decisions[i])
                }
            }
        },
        // 根据所选决策项选择部门或者人（在本页面调取选人接口：如果只有一个人默认展示，否则跳页面选择人）
        getOrgAndUser(appDecision) {
            console.log('sub' + '11111111111')
            // 待办流程的下一步
            dyytGetNextUser(
                Object.assign(this.params, {
                    decisiondata: appDecision,
                    userName: this.user.userName,
                })
            ).then((res) => {

                if (res.data.data && res.data.data.length > 0) {
                    if (
                        this.decision == 'end' ||
                        (this.decision.indexOf('end') > -1)
                    ) {
                        this.selectData = {
                            treeType: res.data.data[0].display,
                            group: res.data.data[0].group,
                            value: ''
                        }
                    } else {
                        if (res.data.data[0].user && res.data.data[0].user.length > 0) {
                            var resUser = res.data.data[0].user
                            var uList = [] // 人
                            var oList = [] // 组织
                            var ouObj = {} // 组织对象
                            for (var i in resUser) {
                                if (resUser[i].treeType == 'user') {
                                    uList.push(resUser[i])
                                }
                                if (resUser[i].treeType == 'org') {
                                    oList.push(resUser[i])
                                    ouObj[resUser[i].id] = resUser[i]
                                }
                            }
                            if (uList.length == 1) {
                                this.uListName = uList[0].name + "123"
                                this.selectData = uList[0]
                                this.selectData.group = res.data.data[0].group
                                this.params.appDecision = appDecision
                            } else {
                                // 跳页面选人
                                var getOrgAndUserName = "支部近期学习重点";
                                this.$router.push({
                                    name: 'getOrgAndUser',
                                    query: {
                                        type: this.params.type,
                                        applyType: this.params.applyType,
                                        location: this.params.location,
                                        processInstId: this.params.processInstId,
                                        processDefName: this.params.processDefName,
                                        workItemId: this.params.workItemId,
                                        drawUpType: this.params.drawUpType,
                                        appDecision: appDecision,
                                        currentDecision: this.decisionRadio,
                                        formData: this.params.formData,
                                        isCopy: 'false',
                                        oldParams: this.params,
                                        peopledata: res.data,
                                        getOrgAndUserName: getOrgAndUserName
                                    }
                                })
                            }
                        } else {
                            Notify({
                                type: 'warning',
                                message: '当前决策项下无数据，请选择其他决策项',
                                duration: 1300
                            })
                        }
                    }
                }
            })
        },

        // 选择抄送人员
        toSelectCopy() {
            if (this.params.type) {
                // 待办流程的下一步
                getOrgAndUser({
                    applyType: this.params.applyType,
                    location: this.params.location,
                    processInstId: this.params.processInstId,
                    appDecision: this.copyDecision
                }).then((res) => {
                    if (res.data && res.data.length > 0) {
                        if (res.data[0].user && res.data[0].user.length > 0) {
                            var resUser = res.data[0].user
                            var uList = [] // 人
                            var oList = [] // 组织
                            var ouObj = {} // 组织对象
                            for (var i in resUser) {
                                if (resUser[i].treeType == 'user') {
                                    uList.push(resUser[i])
                                }
                                if (resUser[i].treeType == 'org') {
                                    oList.push(resUser[i])
                                    ouObj[resUser[i].id] = resUser[i]
                                }
                            }
                            if (uList.length == 1) {
                                this.copyList = uList
                            } else {
                                // 跳页面选人
                                this.$router.push({
                                    name: 'getOrgAndUser',
                                    params: {
                                        applyType: this.params.applyType,
                                        location: this.params.location,
                                        processInstId: this.params.processInstId,
                                        processDefName: this.params.processDefName,
                                        workItemId: this.params.workItemId,
                                        type: this.params.type,
                                        appDecision: this.copyDecision,
                                        oldAppDecision: this.params.appDecision,
                                        currentDecision: this.decisionRadio,
                                        formData: this.params.formData,
                                        isCopy: 'true',
                                        selectPeople: this.selectData,
                                        oldParams: this.params
                                    }
                                })
                            }
                        } else {
                            Notify({
                                type: 'warning',
                                message: '抱歉，暂无抄送人员可供选择',
                                duration: 1300
                            })
                        }
                    }
                })
            } else {
                // 起草下一步
                getOrgAndUser({
                    applyType: this.params.applyType,
                    location: this.params.location,
                    appDecision: this.copyDecision
                }).then((res) => {
                    if (res.data && res.data.length > 0) {
                        if (res.data[0].user && res.data[0].user.length > 0) {
                            var resUser = res.data[0].user
                            var uList = [] // 人
                            var oList = [] // 组织
                            var ouObj = {} // 组织对象
                            for (var i in resUser) {
                                if (resUser[i].treeType == 'user') {
                                    uList.push(resUser[i])
                                }
                                if (resUser[i].treeType == 'org') {
                                    oList.push(resUser[i])
                                    ouObj[resUser[i].id] = resUser[i]
                                }
                            }
                            if (uList.length == 1) {
                                this.copyList = uList
                            } else {
                                // 跳页面选人
                                this.$router.push({
                                    name: 'getOrgAndUser',
                                    params: {
                                        applyType: this.params.applyType,
                                        location: this.params.location,
                                        appDecision: this.copyDecision,
                                        oldAppDecision: this.params.appDecision,
                                        currentDecision: this.decisionRadio,
                                        formData: this.params.formData,
                                        isCopy: 'true',
                                        selectPeople: this.selectData
                                    }
                                })
                            }
                        } else {
                            Notify({
                                type: 'warning',
                                message: '抱歉，暂无抄送人员可供选择',
                                duration: 1300
                            })
                        }
                    }
                })
            }
        },

        // 提交
        submitClick(e) {
            if (this.message == '') {
                Notify({ type: 'warning', message: '请填写审批意见', duration: 1300 })
            } else if (!this.selectData && this.decision != 'end') {
                Notify({
                    type: 'warning',
                    message: '请选择办理人员或部门',
                    duration: 1300
                })
            } else {
                // 执行提交
                this.goNext()
            }
        },

        goNext() {
            this.isSubmit = true
            var submitParams = {}
            if (
                this.params.isCopy &&
                this.params.isCopy == 'true' &&
                this.copyList.length > 0
            ) {
                submitParams.outcome = this.params.oldAppDecision.decisionId
                submitParams.copyLocation = this.params.appDecision.decisionId
            } else {
                if (this.decision == 'end' || this.decision.indexOf('end') > -1) {
                    // 审批归档
                    if (this.decision == 'end') {
                        submitParams.outcome = 'end'
                    }
                    if (this.decision.indexOf('end') > -1) {
                        submitParams.outcome = this.decision
                    }
                } else {
                    submitParams.outcome = this.params.appDecision.decisionId
                }
                submitParams.copyLocation = ''
            }
            // submitParams.source = this.params.source;
            // this.$store.state.user.user.username
            submitParams.currentUserCode = this.user.username
            // 流程审批提交多三个字段
            if (this.params.type) {
                if (this.params.type == 'toRead') {
                    submitParams.notificationId = this.params.notificationId
                } else {
                    submitParams.workItemId = this.params.workItemId
                }
                submitParams.processInstId = this.params.processInstId
                submitParams.location = this.params.location
            }
            // 请求体里的对象
            var flowParam2 = {
                flowParam: {}
            }
            if (
                this.params.isCopy &&
                this.params.isCopy == 'true' &&
                this.copyList.length > 0
            ) {
                // 提交的抄送人数据
                var cList = []
                for (var i in this.copyList) {
                    let a = this.copyList[i].id + '-' + this.copyList[i].name
                    cList.push(a)
                }
                var cstr = cList.join(',')
                flowParam2.flowParam.copyMessage = '请阅示'
                flowParam2.flowParam.copyNextUserNames = [
                    {
                        display: this.copyList[0].treeType,
                        group: this.copyList[0].group,
                        value: cstr
                    }
                ]
            } else {
                flowParam2.flowParam.copyMessage = ''
                flowParam2.flowParam.copyNextUserNames = []
            }
            if (
                this.params.isCopy &&
                this.params.isCopy == 'true' &&
                this.copyList.length > 0
            ) {
                flowParam2.flowParam.decisionId = this.params.oldAppDecision.decisionId
            } else {
                if (this.decision == 'end' || this.decision.indexOf('end') > -1) {
                    if (this.decision == 'end') {
                        flowParam2.flowParam.decisionId = 'end'
                    }
                    if (this.decision.indexOf('end') > -1) {
                        flowParam2.flowParam.decisionId = this.decision
                    }
                } else {
                    flowParam2.flowParam.decisionId = this.params.appDecision.decisionId
                }
            }
            flowParam2.flowParam.formData = this.params.formData
            flowParam2.flowParam.message = this.message
            if (this.selectData) {
                // 由于决策项出人接口可能会有问题，所以我们先判断是否存在
                if (this.selectData.length > 0) {
                    // 需要会签，会签是选多个组织（其实还是对应的多个人）
                    var vh = []
                    for (var i in this.selectData) {
                        vh.push(this.selectData[i].id)
                    }
                    flowParam2.flowParam.nextUserName = [
                        {
                            display: 'orguser', // 暂时先定只有会签是多个人，先将这个写死
                            group: this.selectData[0].group,
                            value: vh.join(',')
                        }
                    ]
                } else {
                    // 选的是单个人
                    flowParam2.flowParam.nextUserName = [
                        {
                            display: this.selectData.treeType,
                            group: this.selectData.group,
                            value: this.selectData.id
                        }
                    ]
                }
                submitParams.flowParam = flowParam2
                submitParams.outcomeName = this.message

                console.log('提交参数', submitParams)
                dyytSubmitProcess(Object.assign(submitParams, this.params, { userName: this.user.userName }, { processType: this.params.processType }))
                    .then((res) => {
                        this.isSubmit = false
                        if (res.data.errcode == 0) {
                            if (this.params.idcode.fromMoa) {
                                this.moaBridge_ha_djfupt.closeDoc({
                                    refresh: true,
                                    appcode: "djfupt",
                                });
                            } else {
                                Notify({ type: 'success', message: '提交成功' })
                                this.$router.replace({ path: '/dwdyyt/dwdyytTable' });
                            }

                        } else {
                            Notify(res.message);
                        }
                    })
                    .catch((error) => {
                        this.isSubmit = false
                        Notify({ type: 'warning', message: '提交失败,请稍后重试' })
                    })

                // if (this.params.processType == 'C') {
                //   gzStartSubmitModifyProcess(submitParams)
                // .then((res) => {
                //   this.isSubmit = false
                //   this.$router.replace({ path: '/home' })
                // })
                // .catch((error) => {
                //   this.isSubmit = false
                //   Notify({ type: 'warning', message: '提交失败,请稍后重试' })
                // })
                // } else {
                //   gzStartSubmitProcess(submitParams)
                //     .then((res) => {
                //       this.isSubmit = false
                //       this.$router.replace({ path: '/home' })
                //     })
                //     .catch((error) => {
                //       this.isSubmit = false
                //       Notify({ type: 'warning', message: '提交失败,请稍后重试' })
                //     })
                // }
            } else {
                this.isSubmit = false
                Notify({ type: 'warning', message: '流程异常,请联系管理员' })
            }
            if (localStorage.getItem('history')) {
                localStorage.removeItem('history')
            }
        }
    },
    destroyed() {
        console.log('销毁页面');
        localStorage.setItem('checkboxResultItem', "");
        localStorage.setItem('selectListItem', "");
    }
}
</script>
<style scoped>
.border-b-1 {
    border-bottom: 1px solid #eee;
}

.ht40 {
    width: 100%;
    height: 50px;
    line-height: 50px;
    padding-left: 16px;
    border-bottom: 1px solid #eee;
}

.addOp {
    width: 100%;
    height: 40px;
    line-height: 40px;
    padding-left: 16px;
    font-size: unset;
    vertical-align: middle;
    display: table-cell;
}

.bge {
    width: 100%;
    height: 8px;
    background: #eee;
}

.decisionList {
    width: 100%;
}

.ht46 {
    height: 46px;
    line-height: 46px;
}

.pof-btn {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
}

.copyDiv {
    width: 100%;
    padding: 16px;
}

.van-button--default {
    color: #fff;
    background-color: #7abcf8;
    border: 1px solid #ebedf0;
}
</style>
